import 'package:flutter/material.dart';
import '../repositories/app_state_repository.dart';

class AppStateProvider extends ChangeNotifier {
  final AppStateRepository _repository;
  DateTime _relationshipStartDate = DateTime.now();
  String _partnerName1 = '👩';
  String _partnerName2 = '👨';
  bool _isLoading = false;
  String? _error;
  
  DateTime get relationshipStartDate => _relationshipStartDate;
  String get partnerName1 => _partnerName1;
  String get partnerName2 => _partnerName2;
  bool get isLoading => _isLoading;
  String? get error => _error;
  
  int get daysInRelationship {
    return DateTime.now().difference(_relationshipStartDate).inDays + 1;
  }

  AppStateProvider(this._repository) {
    _loadData();
  }

  Future<void> _loadData() async {
    _setLoading(true);
    
    try {
      final startDateResponse = await _repository.getRelationshipStartDate();
      if (startDateResponse.isSuccess && startDateResponse.data != null) {
        _relationshipStartDate = startDateResponse.data!;
      }
      
      final name1Response = await _repository.getPartnerName1();
      if (name1Response.isSuccess && name1Response.data != null) {
        _partnerName1 = name1Response.data!;
      }
      
      final name2Response = await _repository.getPartnerName2();
      if (name2Response.isSuccess && name2Response.data != null) {
        _partnerName2 = name2Response.data!;
      }
      
      _clearError();
    } catch (e) {
      _setError('加载数据失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> setRelationshipStartDate(DateTime date) async {
    _setLoading(true);
    
    try {
      final response = await _repository.setRelationshipStartDate(date);
      if (response.isSuccess) {
        _relationshipStartDate = date;
        _clearError();
      } else {
        _setError(response.error ?? '设置关系开始日期失败');
      }
    } catch (e) {
      _setError('设置关系开始日期失败: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> setPartnerNames(String name1, String name2) async {
    _setLoading(true);
    
    try {
      final response = await _repository.setPartnerNames(name1, name2);
      if (response.isSuccess) {
        _partnerName1 = name1;
        _partnerName2 = name2;
        _clearError();
      } else {
        _setError(response.error ?? '设置伴侣姓名失败');
      }
    } catch (e) {
      _setError('设置伴侣姓名失败: $e');
    } finally {
      _setLoading(false);
    }
  }
  
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
  
  void _setError(String error) {
    _error = error;
    notifyListeners();
  }
  
  void _clearError() {
    _error = null;
    notifyListeners();
  }
}